package org.example.day07;

import java.util.ArrayList;
import java.util.List;

/**
 * 第三章节3.1.1: 不使用wait/notify机制进行通信的缺点
 *      线程B不断的通过轮询来检测某个被A线程写入的值
 *      缺点:太浪费CPU资源
 **/
public class MyThread {
    volatile private List list = new ArrayList<>(); //让多个线程同步该变量，保持可见性
    public void add(){
        list.add("三笠");
    }
    public int size(){
        return list.size();
    }

    public static void main(String[] args) {
        MyThread m1 = new MyThread();
        Thread1A ta = new Thread1A(m1);
        ta.setName("A");
        ta.start();
        Thread1B tb = new Thread1B(m1);
        tb.setName("B");
        tb.start();
    }
}

class Thread1A extends Thread{
    private MyThread m1;

    public Thread1A(MyThread m1) {
        this.m1 = m1;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                m1.add();
                System.out.println("添加了 " + (i+1) + "个元素");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread1B extends Thread{
    private MyThread m1;

    public Thread1B(MyThread m1) {
        this.m1 = m1;
    }

    @Override
    public void run() {
        try {
            while(true){
                if(m1.size() == 5){
                    System.out.println("等于5就退出~");
                    throw new InterruptedException();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}